package com.lntea.netty.chat;

import com.lntea.netty.demo.diff.echo.EchoConstant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * Title: LiClientHandler.java<br>
 * Description:  <br>
 *
 * @author LC
 * @date 2020/9/24 15:51
 */
public class LiClientHandler extends ChannelInboundHandlerAdapter {
    private int dialogId;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 双工模式，循环发送开场白
        new Thread(() -> {
            while(dialogId++ < 50) {
                //ByteBuf message = Unpooled.copiedBuffer("server dialog", CharsetUtil.UTF_8);
                //System.out.println(message.toString(CharsetUtil.UTF_8));
                HuTongMessage message = new HuTongMessage(dialogId, HuTongChatEnum.LI_2.getDialog());
                System.out.println(message.toString());
                ctx.writeAndFlush(message);
                HuTongMessage message2 = new HuTongMessage(dialogId, HuTongChatEnum.LI_3.getDialog());
                System.out.println(message2.toString());
                ctx.writeAndFlush(message2);
            }
        }).start();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //ByteBuf message = (ByteBuf) msg;
        //System.out.println(message.toString(CharsetUtil.UTF_8));
        HuTongMessage message = (HuTongMessage) msg;
        if (message.getMsgContent() == null) {
            ctx.flush();
        }
        message.setMsgContent(HuTongChatEnum.nextDialog(message.getMsgContent()));
        System.out.println(message.toString());
        ctx.writeAndFlush(message);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        // ctx.close();
    }
}
